<style lang="less" scoped>
@import "@/assets/style/variables.less";

.banner {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: @border-radius;
    box-shadow: @box-shadow;
    padding: @padd;
    position: relative;

    .banner-form {
        margin-top: 15px;
    }

    .block {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 30px;
    }

    .banner-table {
        border-radius: 5px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        margin-top: 20px;
    }

    .banner-form,
    .banner-table {
        .opt {
            margin-bottom: 15px;
        }

        .preview-img {
            width: 360px;
            height: 180px;
        }

        .el-upload-list {
            display: none;
        }


    }



    .preview-img {
        margin-top: 20px;
        border-radius: 5px;
        width: 100%;
    }


    .upload-demo {
        width: 100%;
        margin-top: 20px;

    }

    ::v-deep .el-upload {
        width: 100% !important;
    }

    ::v-deep .el-upload-dragger {
        width: 100% !important;
    }
}

.my-input {
    width: 100% !important;
    height: 28px;
    line-height: 28px;
    -webkit-appearance: none;
    background-color: #FFF;
    background-image: none;
    border: 1px solid #DCDFE6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: 0;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645, .045, .355, 1);
    width: 100%;
    border-radius: 4px;
}
</style>
<template>
    <div class="banner">
        <div class="banner-header">
            <el-button size="small" :type="num == 1 ? 'danger' : ''" @click="num = 1">发布相册</el-button>
            <el-button size="small" :type="num == 2 ? 'danger' : ''" @click="num = 2">相册列表</el-button>
        </div>
        <div v-if="num == 1" class="banner-form">
            <div class="opt">
                <el-input v-model="photoTitle" placeholder="请输入相册标题"></el-input>
            </div>
            <div class="opt" style="display: flex;">
                <el-upload class="upload-demo" drag action="" :on-change="changeFn" :autoUpload="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>

                <div v-if="src" class="opt-right" style="text-align: center; margin-left: 15px">
                    <img class="preview-img" :src="src" alt="">
                </div>
            </div>
            <div class="opt">
                <el-button type="primary" @click="submitPhotoFn">点击发布</el-button>
            </div>
        </div>
        <div v-if="num == 2" class="banner-table">
            <el-table border :data="tableData" style="width: 100%">
                <el-table-column align="center" label="序号" width="80">
                    <template slot-scope="scope">
                        <span>{{ scope.$index + 1 }}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="ID" prop="id" width="80"></el-table-column>

                <el-table-column align="center" label="标题" prop="photo_title"></el-table-column>
                <el-table-column align="center" label="日期" prop="createAt"></el-table-column>
                <el-table-column align="center" label="图片">
                    <template slot-scope="scope">
                        <div class="demo-image__preview">
                            <el-image style="width: 150px; height: 100px" :src="scope.row.photo_url"
                                :preview-src-list="[scope.row.photo_url]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column align="right">
                    <template slot="header">
                        <input type="text" placeholder="关键字" class="my-input" v-model="search">
                    </template>
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="num == 2" class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[4, 5, 6, 7]" :page-size="page_size"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <div>
            <el-dialog title="修改相册列表" :visible.sync="centerDialogVisible" width="30%" center>
                <div>
                    <div class="opt">
                        <el-input v-model="editForm.photo_title" placeholder="请输入相册标题"></el-input>
                    </div>
                    <div class="photo-updata opt">
                        <el-upload class="p upload-demo" drag action="" :on-change="editChangeFn" :autoUpload="false">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>

                        <div v-if="editForm.photo_url" class="p opt-right" style="text-align: center;">
                            <img class="preview-img" :src="editForm.photo_url" alt="">
                        </div>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取 消</el-button>
                    <el-button @click="saveEdit" type="primary">保存修改</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
// 导入api
import { Message, MessageBox } from 'element-ui';
import { publishPicture, searchPicture, modifyPicture, removePicture, itemsPicture, host, uploadPhoto } from '../api/index'


export default {
    data() {
        return {
            centerDialogVisible: false,
            photoTitle: '',
            src: "",
            tableData: [],
            search: '',// 用于获取输入框的值
            num: 2,
            file: null,
            // 编辑表单数据
            editForm: {
                id: '',
                photo_title: '',
                photo_url: '',
                file: null
            },
            id: "",//相册的id
            // 评论的总数
            total: 0,
            // 前往的页数
            currentPage: 1,
            page_num: 1,
            page_size: 4,
            timer: null,
            photo_url: '',

            // 防抖定时器
            timer2: null
        }
    },
    // 组件销毁前清理定时器
    beforeDestroy() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
        if (this.timer2) {
            clearTimeout(this.timer2);
        }
    },
    methods: {
        // 保存编辑
        async saveEdit() {
            if (this.editForm.photo_title.trim() == '') {
                Message({
                    showClose: true,
                    message: '你还没输入呢~~',
                    type: 'error',
                    offset: 100
                })
                return
            }
            try {
                let photo_url = this.editForm.photo_url
                // console.log(photo_url);
                if (this.editForm.file) {
                    let formData = new FormData()
                    formData.append('photo', this.editForm.file)
                    const uploadResult = await uploadPhoto(formData)
                    // console.log(uploadResult);
                    // 添加检查确保 uploadResult 和 uploadResult.data 存在
                    if (uploadResult && uploadResult.data && uploadResult.data.photo_url) {
                        photo_url = uploadResult.data.photo_url
                    } else if (uploadResult && uploadResult.picUrl) {
                        // 如果返回的是 picUrl 字段
                        photo_url = uploadResult.picUrl
                    } else {
                        // 如果两种格式都不存在，抛出错误
                        throw new Error('上传图片失败，未返回有效的图片URL')
                    }
                }
                // console.log(this.editForm);
                await this.modifyPictureFn(
                    this.editForm.id,
                    this.editForm.photo_title,
                    photo_url
                )
                // 关闭对话框
                this.centerDialogVisible = false
            } catch (error) {
                Message({
                    showClose: true,
                    message: '保存失败',
                    type: 'error',
                    offset: 100
                })
                console.log(error);
            }
        },
        // 编辑时的图片预览
        editChangeFn(info) {
            let file = info.raw;
            const reader = new FileReader();
            reader.onload = () => {
                // 更新编辑表单的预览图片和文件
                this.editForm.photo_url = reader.result;
                this.editForm.file = file;
            }
            if (file) {
                reader.readAsDataURL(file);
            }
            return false;
        },

        // 修改相册接口函数
        async modifyPictureFn(id, photo_title, photo_url) {
            // console.log({ id, photo_title, photo_url })
            // console.log(host);
            if (photo_url.includes(host)) {
                photo_url = photo_url.replace(host, '')
            }
            // console.log(photo_url);
            await modifyPicture({ id, photo_title, photo_url })
                .then(
                    res => {
                        // console.log(res);
                        if (res.code == 200) {
                            Message({
                                showClose: true,
                                message: '修改成功',
                                type: 'success',
                                offset: 100
                            });
                            this.itemsPictureFn()
                            this.centerDialogVisible = false
                        } else {
                            Message({
                                showClose: true,
                                message: '修改失败',
                                type: 'error',
                                offset: 100
                            });

                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '修改失败',
                            type: 'error',
                            offset: 100
                        });
                        console.log(err);
                    }
                )
        },
        // 分页
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.page_size = val
            this.page_num = 1;
            this.itemsPictureFn()
        },
        // 当前的页数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.page_num = val
            this.currentPage = val;
            this.itemsPictureFn()
        },
        // 编写搜索方法
        async searchPictureFn(keyword) {
            if (keyword == '' || keyword == null) {
                this.itemsPictureFn()
                return
            }
            await searchPicture({ keyword })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.tableData = res.result.map(item => {
                                item.photo_url = host + item.photo_url;
                                item.createAt = this.formatime(item.createAt)
                                return item;
                            })
                            Message({
                                showClose: true,
                                message: '搜索成功',
                                type: 'success',
                                offset: 100
                            })
                            this.total = res.result.length
                        } else {
                            Message({
                                showClose: true,
                                message: '暂无该相册',
                                type: 'error',
                                offset: 100
                            })
                        }
                    }, err => {
                        Message({
                            showClose: true,
                            message: '服务器错误',
                            type: 'error',
                            offset: 100
                        })
                        console.log(err)
                    }
                )
        },
        // 删除相册
        async removePhotoFn(id) {
            // console.log(id);
            try {
                await MessageBox.confirm("您确定要删除该记录吗?", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
                const res = await removePicture({ id })
                if (res.code == 200) {
                    Message({
                        type: 'success',
                        message: "删除成功~",
                        showClose: true
                    });
                    this.itemsPictureFn();
                } else {
                    Message({
                        type: 'error',
                        message: "删除失败~",
                        showClose: true
                    });
                }
            } catch (err) {
                return false;
            }
        },

        // 获取相册列表

        async itemsPictureFn() {
            await itemsPicture({ page_num: this.page_num, page_size: this.page_size })
                .then(
                    res => {
                        // console.log(res)
                        if (res.code == 200) {
                            this.tableData = res.result.map(item => {
                                item.photo_url = host + item.photo_url;
                                item.createAt = this.formatime(item.createAt)
                                return item;
                            })
                            // console.log(this.tableData)
                            this.total = res.total;
                        }
                    }, err => {
                        console.log(err)
                    }
                )
        },
        // 点击发布相册
        async submitPhotoFn() {
            if (this.photoTitle == '') {
                Message({
                    type: 'error',
                    message: "你还没写呢~",
                    showClose: true
                })
                return false;
            }
            if (this.src == '') {
                Message({
                    type: 'error',
                    message: "请上传相册",
                    showClose: true
                })
                return false;
            }
            let result = await this.uploadPhotoFn();
            // console.log('相册', result);
            await publishPicture({ photo_title: this.photoTitle, photo_url: result.picUrl })
                .then(
                    async res => {
                        if (res.code == 200) {
                            Message({
                                type: 'success',
                                message: "发布成功",
                                showClose: true
                            })
                            await this.itemsPictureFn()
                            // 清除之前的定时器
                            if (this.timer) {
                                clearTimeout(this.timer)
                            }
                            // 设置新的定时器
                            this.timer = setTimeout(() => {
                                this.num = 2
                                this.photoTitle = ''
                                this.timer = null  // 清空引用
                            }, 500)
                        } else {
                            Message({
                                type: 'error',
                                message: "发布失败",
                                showClose: true
                            })
                        }
                    },
                    err => {
                        Message({
                            type: 'error',
                            message: "发布失败",
                            showClose: true
                        })
                        console.log(err);
                    }
                )
        },

        // 编辑
        handleEdit(row) {
            // console.log(row);
            // 显示对话框
            this.centerDialogVisible = true;
            // 初始化编辑表单数据
            this.editForm = {
                id: row.id,
                photo_title: row.photo_title,
                photo_url: row.photo_url,
                file: null
            };
        },
        // 删除
        async handleDelete(row) {
            // console.log(row);
            if (row.id) {
                await this.removePhotoFn(row.id);// 删除记录
            }
        },
        // 上传图片
        async uploadPhotoFn() {
            // 采集信息的构造函数
            let formData = new FormData()
            formData.append('photo', this.file)
            return await uploadPhoto(formData)
        },
        // 预览图片
        changeFn(info) {
            // console.dir(info);// 图片信息对象
            // 读取单个文件
            let file = info.raw;
            const reader = new FileReader();
            reader.onload = () => {
                // 将图像文件转换为 Base64 字符串
                //  console.log(reader.result);
                this.src = reader.result;
            }
            if (file) {
                // 记录图片信息
                this.file = file;
                reader.readAsDataURL(file);
            }
            return false;
        },
    },
    // 初始化
    created() {
        this.itemsPictureFn()
    },
    watch: {
        $route: {
            immediate: true,
            deep: true,
            handler(newRoute) {
                // console.log(newRoute);
                this.$store.commit("addTab", newRoute);
            }
        },
        // 观察输入框的变化
        search: function (newKeyword) {
            // 执行搜索方法
            // console.log(newKeyword);
            let keyword = newKeyword
            // 清除之前的定时器
            if (this.timer2) {
                clearTimeout(this.timer2)
            }
            if (keyword.trim() === '') {
                this.itemsPictureFn()
                return
            }
            this.timer2 = setTimeout(() => {
                this.searchPictureFn(keyword)
                this.timer2 = null
            }, 500)

        }
    }
}
</script>